package com.itheima.reggie_auto.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie_auto.entity.Category;
import com.itheima.reggie_auto.entity.Dish;
import com.itheima.reggie_auto.entity.Setmeal;
import com.itheima.reggie_auto.exception.CustomException;
import com.itheima.reggie_auto.mapper.CategoryMapper;
import com.itheima.reggie_auto.mapper.DishMapper;
import com.itheima.reggie_auto.mapper.SetmealMapper;
import com.itheima.reggie_auto.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;


    @Override
    public Page<Category> page(int page, int pageSize) {
        //创建分页构造器
        Page<Category> pageInfo = new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        categoryMapper.selectPage(pageInfo,lqw);
        return pageInfo;
    }

    @Override
    public void save(Category category) {
        categoryMapper.insert(category);
    }

    @Override
    public void deleteById(Long id) {
        //删除操作 主表删除必须考虑从表是否有值 有值不能删，无值才能删

        //1.判断该分类是否存在菜品或者套餐

        LambdaQueryWrapper<Setmeal> setmealLqw = new LambdaQueryWrapper<>();
        setmealLqw.eq(Setmeal::getCategoryId,id);
        Integer smcount = setmealMapper.selectCount(setmealLqw);
        if (smcount > 0) {
            //套餐表有值，不能删
            throw new CustomException("该分类下有套餐，不能删除");
        }

        LambdaQueryWrapper<Dish> dishLqw = new LambdaQueryWrapper<>();
        dishLqw.eq(Dish::getCategoryId,id);
        Integer count = dishMapper.selectCount(dishLqw);
        if (count > 0) {
            //菜品表有值，不能删
            throw new CustomException("该分类下有菜品，不能删除");
        }


        //删除操作
        categoryMapper.deleteById(id);

    }

    @Override
    public void update(Category category) {
        categoryMapper.updateById(category);
    }

    @Override
    public List<Category> getList(Category category) {
        //分析：  条件type = 1  按sort升序  修改时间降序
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(category.getType()!=null,Category::getType,category.getType());
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> categoryList = categoryMapper.selectList(lqw);
        return categoryList;
    }

    @Override
    public Category getById(Long categoryId) {
        return categoryMapper.selectById(categoryId);
    }
}
